package com.lcw.library.imagepicker.loader;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.data.resultset.ResultSet;
import ohos.utils.net.Uri;

import java.util.ArrayList;

/**
 * 媒体库查询任务基类
 * Create by: chenWei.li
 * Date: 2019/1/21
 * Time: 8:35 PM
 * Email: lichenwei.me@foxmail.com
 */
public abstract class AbsMediaScanner<T> {
    /**
     * Query URI
     *
     * @return uri
     */
    protected abstract Uri getScanUri();

    /**
     * Query Column Name
     *
     * @return string array
     */
    protected abstract String[] getProjection();

    /**
     * Search criteria
     *
     * @return string
     */
    protected abstract String getSelection();

    /**
     * Query condition value.
     *
     * @return string array
     */
    protected abstract String[] getSelectionArgs();

    /**
     * Query Sorting
     *
     * @return string
     */
    protected abstract String getOrder();

    /**
     * Expose cursors to external systems, allowing developers to flexibly build objects.
     *
     * @param cursor
     * @return t
     */
    protected abstract T parse(ResultSet cursor);

    private Context mContext;

    AbsMediaScanner(Context context) {
        this.mContext = context;
    }

    public ArrayList<T> queryMedia() {
        try {
            ArrayList<T> list = new ArrayList<>();
            DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(mContext);

            ResultSet resultSet = dataAbilityHelper.query(getScanUri(), getProjection(), null);
            if (resultSet != null) {
                while (resultSet.goToNextRow()) {
                    T t = parse(resultSet);
                    list.add(t);
                }
                resultSet.close();
            }
            return list;
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        return null;
    }
}
